package cn.tqfeiyang.smartadmin.system.mapper;

import cn.tqfeiyang.smartadmin.system.entity.*;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Set;

/**
 * 用户-角色映射接口
 *
 * @author tqfeiyang
 * @since 2024/8/20 14:15
 */
@Mapper
public interface UserRoleMapper extends BaseMapper<UserRoleEntity> {

    @Select("SELECT r.* FROM sys_user_role ur JOIN sys_role r ON r.role_id = ur.role_id WHERE ur.user_id = #{userId}")
    List<RoleEntity> selectRoleListByUserId(Long userId);

    @Insert("<script>"
            + "INSERT INTO sys_user_role(user_id, role_id) "
            + "SELECT #{userId}, role_id "
            + "FROM sys_role "
            + "WHERE role_id IN "
            + "<foreach item='id' index='index' collection='roleIds' open='(' separator=',' close=')'>"
            + "#{id}"
            + "</foreach>"
            + "</script>")
    int insertRoleIdsByUserId(Long userId, Set<Long> roleIds);

    @Delete("DELETE FROM sys_user_role WHERE user_id = #{userId}")
    void deleteRoleIdsByUserId(Long userId);

    @Select("SELECT u.* FROM sys_user_role ur JOIN sys_user u ON u.user_id = ur.user_id WHERE ur.role_id = #{roleId}")
    List<UserEntity> selectUserListByRoleId(Long roleId);

    @Insert("<script>"
            + "INSERT INTO sys_user_role(role_id, user_id) "
            + "SELECT #{roleId}, user_id "
            + "FROM sys_user "
            + "WHERE user_id IN "
            + "<foreach item='id' index='index' collection='userIds' open='(' separator=',' close=')'>"
            + "#{id}"
            + "</foreach>"
            + "</script>")
    int insertUserIdsByRoled(Long roleId, Set<Long> userIds);

    @Delete("DELETE FROM sys_user_role WHERE role_id = #{roleId}")
    void deleteUserIdsByRoleId(Long roleId);

    @Select("SELECT p.* FROM sys_user_role ur JOIN sys_role_permission rp ON rp.role_id = ur.role_id JOIN sys_permission p ON p.permission_id = rp.permission_id WHERE ur.user_id = #{userId}")
    List<PermissionEntity> selectPermissionListByUserId(Long userId);

    @Select("SELECT m.* FROM sys_user_role ur JOIN sys_role_menu rm ON rm.role_id = ur.role_id JOIN sys_menu m ON m.menu_id = rm.menu_id WHERE ur.user_id = #{userId}")
    List<MenuEntity> selectMenuListByUserId(Long userId);

}
